package com.xmjs.baselibrary.network.Interceptor;

import com.xmjs.baselibrary.utils.LocalCache;
import com.xmjs.baselibrary.utils.SP;

import java.io.IOException;

import io.reactivex.Observable;
import okhttp3.Interceptor;
import okhttp3.Response;

/**
 * 响应拦截器
 */
public class ReceivedInterceptor implements Interceptor {
    private SP sp;

    public ReceivedInterceptor(SP sp) {
        this.sp = sp;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        /**
         * 本地缓存cookie
         */
        Response originalResponse = chain.proceed(chain.request());
        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            final StringBuffer cookieBuffer = new StringBuffer();
            Observable.fromIterable(originalResponse.headers("Set-Cookie"))
                    .map(s -> {
                        String[] cookieArray = s.split(";"); // JSESSIONID=aaaQElHouiqmGh-oaQCtv; path=/
                        return cookieArray[0];
                    })
                    .subscribe(cookie -> {
                        LocalCache.saveCookie(sp, cookie);
                    });
        }
        return originalResponse;
    }
}
